<template>
  <div>
    <div class="city-search">
      <input v-model="keyword" type="text" placeholder="输入城市名或拼音" class="city-input"/>
    </div>
    <div v-show="this.keyword"  class="search-con" ref="search">
      <ul>
        <li
          class="border-bottom search-li"
          v-for="item in list"
          :key="item.id"
          @click="handleHotCity(item.name)"
        >{{item.name}}</li>
        <li class="border-bottom search-li" v-show="hasNoDate">没有匹配的数据</li>
      </ul>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import BScroll from 'better-scroll'
import { mapActions } from 'vuex'
export default{
  name: 'search',
  props: {
    List: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasNoDate () {
      return !this.list.length
    }
  },
  methods: {
    handleHotCity (val) {
      this.$store.dispatch('hotCityChange', val)
      this.$router.push('/')
    },
    ...mapActions(['handleHotCity'])
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.List) {
          this.List[i].forEach((val) => {
            if (val.name.indexOf(this.keyword) > -1 || val.spell.indexOf(this.keyword) > -1) {
              result.push(val)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search)
  }
}
</script>
<style lang="stylus" scoped>
  @import "~styles/varibles";
  .city-search
    background: $bgColor
    height: .72rem
    padding: 0 .2rem
    .city-input
      box-sizing: border-box
      width: $maxWidth
      border-radius: .08rem
      height: .6rem
      padding: 0 .2rem
      text-align: center
      color: #666
  .search-con
    position: absolute
    top: 1.58rem
    right: 0
    left: 0
    bottom: 0
    background: #ccc
    z-index: 1
    overflow: hidden
    .search-li
      line-height: .6rem
      background: #fff
      padding-left: .2rem
</style>
